package org.vigor.lab.gateway.zuul.filter;

import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.web.util.UrlPathHelper;
import org.vigor.lab.gateway.util.RequestAuditLog;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.util.HTTPRequestUtils;

/**
 * LogZuulFilter
 * <p>
 * </p>
 *
 * @author Vigor Yuan
 */
public class LogPreZuulFilter extends ZuulFilter {

    private UrlPathHelper urlPathHelper = new UrlPathHelper();

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return FilterConstants.DEBUG_FILTER_ORDER;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        String requestURI = urlPathHelper.getLookupPathForRequest(ctx.getRequest());
        long currentTimeMillis = System.currentTimeMillis();
        String requestKey = requestURI + "-" + currentTimeMillis;
        ctx.set("requestKey", requestKey);
        ctx.set("currentTimeMillis", currentTimeMillis);
        ctx.setDebugRequest(true);
        ctx.setDebugRouting(true);
        RequestAuditLog.audit("request[{}] URI[{}] method[{}] param[{}]", requestKey, requestURI,
                ctx.getRequest().getMethod(), HTTPRequestUtils.getInstance().getQueryParams());
        return null;
    }
}
